package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebsocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebsocketService websocketService;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.gaode.key}")
    private String key;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        log.info("用户下单：{}", ordersSubmitDTO);
        // 判断地址是否为空
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 向订单表插入数据
        Order order = new Order();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setStatus(Order.PENDING_PAYMENT);
        order.setUserId(BaseContext.getCurrentId());
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Order.UN_PAID);
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        orderMapper.insert(order);
        // 向订单明细表插入数据
        List<OrderDetail> detailList = list.stream().map(s -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(s, orderDetail);
            orderDetail.setOrderId(order.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        detailMapper.insert(detailList);
        // 清空购物车
        shoppingCartMapper.cleanByUserId(BaseContext.getCurrentId());
        // 封装VO并返回
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        // 调用微信支付接口，生成预支付交易单
        OrderPaymentVO vo = null;
        try {
            JSONObject jsonObject = weChatPayUtil.pay(
                    ordersPaymentDTO.getOrderNumber(), // 商户订单号
                    new BigDecimal(0.01), // 支付金额，单位 元
                    "苍穹外卖订单", // 商品描述
                    user.getOpenid() // 微信用户的openid
            );

            if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
                throw new OrderBusinessException("该订单已支付");
            }

            vo = jsonObject.toJavaObject(OrderPaymentVO.class);
            vo.setPackageStr(jsonObject.getString("package"));
        } catch (Exception e) {
            paySuccess(ordersPaymentDTO.getOrderNumber());
            throw new OrderBusinessException("该订单已支付");
        }

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Order orderDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Order order = Order.builder()
                .id(orderDB.getId())
                .status(Order.TO_BE_CONFIRMED)
                .payStatus(Order.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(order);
        // 通过WebSocket，提醒商家有新订单
        Map<String, Object> reminders = new HashMap<>();
        reminders.put("type", 1);// 1表示新订单
        reminders.put("orderId", orderDB.getId());
        reminders.put("content", "订单号：" + outTradeNo);
        websocketService.sendAllClient(JSON.toJSONString(reminders));
    }

    /**
     * 提醒商家有用户催单
     *
     * @param id
     */
    @Override
    public void remind(Long id) {
        // 判断订单是否存在合法
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (Objects.equals(order.getStatus(), Order.PENDING_PAYMENT)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 通过WebSocket，提醒商家有用户催单
        String orderNumber = order.getNumber();
        Map<String, Object> reminders = new HashMap<>();
        reminders.put("type", 2);// 2表示催单
        reminders.put("orderId", id);
        reminders.put("content", "订单号：" + orderNumber);
        websocketService.sendAllClient(JSON.toJSONString(reminders));
    }

    /**
     * 历史订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageOrder(OrdersPageQueryDTO dto) {
        Page<Order> ordersPage = new Page<>(dto.getPage(), dto.getPageSize());
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>()
                .eq(dto.getUserId() != null, Order::getUserId, dto.getUserId())
                .eq(dto.getStatus() != null, Order::getStatus, dto.getStatus())
                .eq(dto.getPhone() != null, Order::getPhone, dto.getPhone())
                .eq(dto.getBeginTime() != null, Order::getOrderTime, dto.getBeginTime())
                .eq(dto.getEndTime() != null, Order::getOrderTime, dto.getEndTime())
                .eq(dto.getNumber() != null && !dto.getNumber().isEmpty(), Order::getNumber, dto.getNumber())
                .orderByDesc(Order::getOrderTime);
        ordersPage = orderMapper.selectPage(ordersPage, queryWrapper);

        // 组成VO
        List<OrderVO> orderVOS = ordersPage.getRecords().stream().map(order -> orderDetail(order.getId())).collect(Collectors.toList());
        return new PageResult(ordersPage.getTotal(), orderVOS);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Order order = orderMapper.selectById(id);
        // 判断订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetails = detailMapper.selectByOrderId(id);
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insert(shoppingCarts);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null || order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (order.getStatus().equals(Order.TO_BE_CONFIRMED)) {
            // try {
            //     weChatPayUtil.refund(
            //             order.getNumber(),
            //             order.getNumber(),
            //             order.getAmount(),
            //             order.getAmount()
            //     );
            // } catch (Exception e) {
            //     throw new RuntimeException(e);
            // }
        }
        Order orderDB = Order.builder()
                .id(id)
                .status(Order.S_REFUND)
                .cancelReason("用户取消")
                .cancelTime(LocalDateTime.now())
                .payStatus(Order.P_S_REFUND)
                .build();
        orderMapper.update(orderDB);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetails = detailMapper.selectByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        // 查询地址
        AddressBook addressBook = addressBookMapper.selectById(order.getAddressBookId());
        String address = addressBook.getProvinceName() +
                addressBook.getCityName() +
                addressBook.getDistrictName() +
                addressBook.getDetail();
        orderVO.setAddress(address);
        return orderVO;
    }

    /**
     * 统计各个状态订单的数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Map<String, Object> map = new HashMap<>();
        // 待接单数量
        map.put("status", Order.TO_BE_CONFIRMED);
        Integer toBeConfirmed = orderMapper.countOrder(map).intValue();
        // 待派送数量
        map.put("status", Order.CONFIRMED);
        Integer confirmed = orderMapper.countOrder(map).intValue();
        // 派送中数量
        map.put("status", Order.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = orderMapper.countOrder(map).intValue();
        return new OrderStatisticsVO(toBeConfirmed, confirmed, deliveryInProgress);
    }

    /**
     * 接单
     *
     * @param dto
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Order order = orderMapper.selectById(dto.getId());
        if (order == null || !Objects.equals(order.getStatus(), Order.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Order orderDB = Order.builder()
                .id(dto.getId())
                .status(Order.CONFIRMED)
                .build();
        orderMapper.update(orderDB);
    }

    /**
     * 拒单
     *
     * @param dto
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Order order = orderMapper.selectById(dto.getId());
        if (order == null || order.getStatus() > Order.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (order.getStatus().equals(Order.TO_BE_CONFIRMED)) {
            // try {
            //     weChatPayUtil.refund(
            //             order.getNumber(),
            //             order.getNumber(),
            //             order.getAmount(),
            //             order.getAmount()
            //     );
            // } catch (Exception e) {
            //     throw new RuntimeException(e);
            // }
        }
        Order orderDB = Order.builder()
                .id(dto.getId())
                .status(Order.S_REFUND)
                .payStatus(Order.P_S_REFUND)
                .cancelReason(dto.getRejectionReason())
                .rejectionReason(dto.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orderDB);
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null || !Objects.equals(order.getStatus(), Order.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Order orderDB = Order.builder()
                .id(id)
                .status(Order.DELIVERY_IN_PROGRESS)
                .estimatedDeliveryTime(LocalDateTime.now().plusMinutes(30))
                .build();
        orderMapper.update(orderDB);
    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null || !Objects.equals(order.getStatus(), Order.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Order orderDB = Order.builder()
                .id(id)
                .status(Order.COMPLETED)
                .build();
        orderMapper.update(orderDB);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map<String, String> map = new HashMap<>();
        // 高德地图API密钥
        map.put("key", key);

        // 获取店铺的经纬度坐标（地理编码）
        map.put("address", shopAddress);
        String shopCoordinate = HttpClientUtil.doGet("https://restapi.amap.com/v3/geocode/geo", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        // 高德地图返回状态码：1表示成功，0表示失败
        if (!"1".equals(jsonObject.getString("status"))) {
            String info = jsonObject.getString("info");
            log.error("高德地图API返回错误，状态码:{}，错误信息:{}", jsonObject.getString("status"), info);
            throw new OrderBusinessException("店铺地址解析失败：" + info);
        }

        // 解析店铺经纬度
        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
        if (geocodes.isEmpty()) {
            throw new OrderBusinessException("未找到店铺地址对应的经纬度");
        }
        String shopLngLat = ((JSONObject) geocodes.get(0)).getString("location");
        // 高德返回格式是 "经度,纬度"，与百度相反

        // 获取用户收货地址的经纬度坐标
        map.put("address", address);
        String userCoordinate = HttpClientUtil.doGet("https://restapi.amap.com/v3/geocode/geo", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!"1".equals(jsonObject.getString("status"))) {
            String info = jsonObject.getString("info");
            log.error("高德地图API返回错误，状态码:{}，错误信息:{}", jsonObject.getString("status"), info);
            throw new OrderBusinessException("收货地址解析失败：" + info);
        }

        // 解析用户地址经纬度
        geocodes = jsonObject.getJSONArray("geocodes");
        if (geocodes.isEmpty()) {
            throw new OrderBusinessException("未找到收货地址对应的经纬度");
        }
        String userLngLat = ((JSONObject) geocodes.get(0)).getString("location");

        // 路线规划 - 驾车路线
        map.clear();
        map.put("key", key);
        map.put("origin", shopLngLat);      // 起点坐标，格式：经度,纬度
        map.put("destination", userLngLat); // 终点坐标，格式：经度,纬度
        map.put("output", "json");

        String json = HttpClientUtil.doGet("https://restapi.amap.com/v3/direction/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!"1".equals(jsonObject.getString("status"))) {
            String info = jsonObject.getString("info");
            log.error("高德地图路径规划API返回错误，状态码:{}，错误信息:{}", jsonObject.getString("status"), info);
            throw new OrderBusinessException("配送路线规划失败：" + info);
        }

        // 解析距离
        JSONObject route = jsonObject.getJSONObject("route");
        JSONArray paths = route.getJSONArray("paths");
        if (paths.isEmpty()) {
            throw new OrderBusinessException("未找到可用配送路线");
        }
        Integer distance = ((JSONObject) paths.get(0)).getInteger("distance");

        if (distance > 5000) {
            log.info("超出配送范围，当前距离：{}米", distance);
            // 配送距离超过5000米
            throw new OrderBusinessException("超出配送范围，当前距离：" + distance + "米");
        }
    }
}